package controller

import (
	"BlazeRider-backend/app/manager"
	"BlazeRider-backend/app/middleware"
	"BlazeRider-backend/app/models"
	"BlazeRider-backend/app/service"
	"BlazeRider-backend/config"
	"BlazeRider-backend/routes"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"regexp"
	"strconv"
)

type dyPushController struct {
}

func NewdyPushController() *dyPushController {
	return &dyPushController{}
}

// controller/http_controller.go
func (h *dyPushController) RegisterRoutes(router *gin.Engine) {
	apiGroup := router.Group("/api/v1")
	{
		//apiGroup.GET("/getToken", h.GetToken)
		// 需要验证 Token 的路由
		authGroup := apiGroup.Group("/dyPush")
		authGroup.Use(middleware.LogRequestMiddleware())
		{
			authGroup.POST("/dyPushPingLun", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyPushPingLun") // 测试路由是否触发
				h.dyPushPingLun(c)
			})

			authGroup.POST("/dyPushGift", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyPushGift") // 测试路由是否触发
				h.dyPushGift(c)
			})

			authGroup.POST("/dyPushZan", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyPushZan") // 测试路由是否触发
				h.dyPushZan(c)
			})

			authGroup.POST("/dyPushFans", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyPushFans") // 测试路由是否触发
				h.dyPushFans(c)
			})

			authGroup.HEAD("/dyPushPingLun", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyPushPingLun") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

			authGroup.HEAD("/dyPushGift", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyPushGift") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

			authGroup.HEAD("/dyPushZan", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyPushZan") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

			authGroup.HEAD("/dyPushFans", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyPushFans") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

			authGroup.POST("/dyGetZhenYing", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyGetZhenYing") // 测试路由是否触发
				h.dyGetZhenYing(c)
			})

			authGroup.POST("/dyPushZhenYing", func(c *gin.Context) {
				fmt.Println("[DEBUG] /dyPushZhenYing") // 测试路由是否触发
				h.dyPushZhenYing(c)
			})

			authGroup.HEAD("/dyGetZhenYing", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyGetZhenYing") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

			authGroup.HEAD("/dyPushZhenYing", func(c *gin.Context) {
				fmt.Println("[DEBUG] get /dyPushZhenYing") // 测试路由是否触发
				c.JSON(http.StatusOK, gin.H{
					"code":    0,
					"message": "success",
					"data":    gin.H{},
				})
			})

		}

	}
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyPushPingLun(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" && XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req []models.CommentOneRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format " + err.Error()})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 检查 X-Msg-Type 的值
	msgType := c.GetHeader("X-Msg-Type")
	if msgType == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no Msg type"})
		return
	}

	// 检查 X-Nonce-Str 的值
	nonceStr := c.GetHeader("X-Nonce-Str")
	if nonceStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no nonce str"})
		return
	}

	// 初始化 转换用户信息
	userInfos := make([]manager.UserInfo, 0, len(req))
	for _, item := range req {
		// 尝试获取已存在的用户信息
		//existingUser, err := manager.Get().UserManager().GetUser(item.SecOpenID)
		//if err != nil {
		// 用户不存在时进行初始化（示例值）
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "user initialization failed"})
			return
		}
		existingUser, _ := manager.Get().UserManager().GetUser(item.SecOpenID)
		//}

		userInfos = append(userInfos, manager.UserInfo{
			UserID:   existingUser.UserID,
			UserName: existingUser.UserName,
			HeadImg:  existingUser.HeadImg,
			Level:    existingUser.Level,
			Rank:     existingUser.Rank,
			Score:    existingUser.Score,
		})
	}

	/* 处理评论数据 */
	// 筛选出加入赛道的数据
	matchStrArray := []string{"1", "2", "3"}

	// 用于存储最终筛选结果（保留最早时间的评论）
	// 定义一个新的切片，保持和原始结构相同的结构
	var finalComments []struct {
		MsgID     string `json:"msg_id"`
		SecOpenID string `json:"sec_openid"`
		Content   string `json:"content"`
		AvatarURL string `json:"avatar_url"`
		Nickname  string `json:"nickname"`
		Timestamp int64  `json:"timestamp"`
	}

	// 用于记录每个 SecOpenID 的最早评论
	secOpenIDMap := make(map[string]struct {
		MsgID     string
		SecOpenID string
		Content   string
		AvatarURL string
		Nickname  string
		Timestamp int64
	})

	// 遍历 req.Arr，筛选符合条件的评论
	for _, item := range req {
		// 检查 Content 是否在 matchStrArray 中
		for _, matchStr := range matchStrArray {
			if item.Content == matchStr {
				// 检查是否已经存在该 SecOpenID 的评论
				if existingItem, exists := secOpenIDMap[item.SecOpenID]; !exists || item.Timestamp < existingItem.Timestamp {
					// 如果不存在，或者当前评论的时间更早，则更新记录
					secOpenIDMap[item.SecOpenID] = struct {
						MsgID     string
						SecOpenID string
						Content   string
						AvatarURL string
						Nickname  string
						Timestamp int64
					}(item)
				}
				break
			}
		}
	}

	// 将 map 中的值转换为切片
	for _, item := range secOpenIDMap {
		finalComments = append(finalComments, struct {
			MsgID     string `json:"msg_id"`
			SecOpenID string `json:"sec_openid"`
			Content   string `json:"content"`
			AvatarURL string `json:"avatar_url"`
			Nickname  string `json:"nickname"`
			Timestamp int64  `json:"timestamp"`
		}{
			MsgID:     item.MsgID,
			SecOpenID: item.SecOpenID,
			Content:   item.Content,
			AvatarURL: item.AvatarURL,
			Nickname:  item.Nickname,
			Timestamp: item.Timestamp,
		})
	}

	for _, item := range finalComments {
		track, _ := strconv.Atoi(item.Content)
		service.LiveRoomService{}.OneUserJoinTrack(roomId, item.SecOpenID, item.Nickname, item.AvatarURL, track, 0)

	}

	// 处理除加入外的互动
	actRegexArray := []*regexp.Regexp{
		regexp.MustCompile(`^6+$`), // 匹配任意长度的全6字符串（如"6", "666"），代表加油
	}

	// finalComments = finalComments[:0] 后，切片可继续存储的元素数量​​上限为原容量值​​，超出时会按 Go 的规则自动扩容（无固定限制，但受内存约束）。复用切片时，此操作是​​高性能最佳实践
	finalComments = finalComments[:0]

	var actMsgList []struct {
		MsgID     string `json:"msg_id"`
		SecOpenID string `json:"sec_openid"`
		Content   string `json:"content"`
		AvatarURL string `json:"avatar_url"`
		Nickname  string `json:"nickname"`
		Timestamp int64  `json:"timestamp"`
	}

	// 遍历 req.Arr，筛选符合条件的评论
	for _, item := range req {
		// 检查 Content 是否在 matchStrArray 中
		for _, reg := range actRegexArray {
			if reg.MatchString(item.Content) {
				// 检查是否已经存在该 SecOpenID 的评论
				actMsgList = append(actMsgList, struct {
					MsgID     string `json:"msg_id"`
					SecOpenID string `json:"sec_openid"`
					Content   string `json:"content"`
					AvatarURL string `json:"avatar_url"`
					Nickname  string `json:"nickname"`
					Timestamp int64  `json:"timestamp"`
				}{
					MsgID:     item.MsgID,
					SecOpenID: item.SecOpenID,
					Content:   item.Content,
					AvatarURL: item.AvatarURL,
					Nickname:  item.Nickname,
					Timestamp: item.Timestamp,
				})
				break
			}
		}
	}

	// 处理非加入轨道类互动评论
	for _, item := range actMsgList {
		if actRegexArray[0].MatchString(item.Content) {
			if err := manager.Get().UserManager().InitializeUser(
				item.SecOpenID,
				item.Nickname,
				item.AvatarURL,
				1, // 初始等级
			); err != nil {

			}
			// 匹配并赠送666字符串的加速
			err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID, "4", 1)
			if err != nil {
			}
		}
	}

	fmt.Println("dyPushPingLun 处理一批评论成功")

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"userInfos":     userInfos,
			"finalComments": finalComments,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyPushGift(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" && XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req []models.GiftRequestPayload
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":  "invalid request format",
			"detail": err.Error(), // 显示具体错误
		})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 检查 X-Msg-Type 的值
	msgType := c.GetHeader("X-Msg-Type")
	if msgType == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no Msg type"})
		return
	}

	// 检查 X-Nonce-Str 的值
	nonceStr := c.GetHeader("X-Nonce-Str")
	if nonceStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no nonce str"})
		return
	}

	for _, item := range req {
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {

		}
		err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID,
			item.SecGiftId, item.GiftNum)
		if err != nil {
			fmt.Println("error: can not send gift error :", err, ", room id : ", roomId, ", msg id : ", item.MsgID)
		}

	}

	fmt.Println("dyPushGift 处理一批礼物通知成功")

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyPushZan(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" && XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req []models.LikeOneRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 检查 X-Msg-Type 的值
	msgType := c.GetHeader("X-Msg-Type")
	if msgType == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no Msg type"})
		return
	}

	// 检查 X-Nonce-Str 的值
	nonceStr := c.GetHeader("X-Nonce-Str")
	if nonceStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no nonce str"})
		return
	}

	for _, item := range req {
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {

		}
		err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID,
			"1", item.LikeNum)
		if err != nil {
		}

	}

	fmt.Println("dyPushZan 处理一批点赞通知成功")

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyPushFans(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" && XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req []models.FansOneRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 检查 X-Msg-Type 的值
	msgType := c.GetHeader("X-Msg-Type")
	if msgType == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no Msg type"})
		return
	}

	// 检查 X-Nonce-Str 的值
	nonceStr := c.GetHeader("X-Nonce-Str")
	if nonceStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no nonce str"})
		return
	}

	for _, item := range req {
		giftId := "2"
		if item.FansClubReasonType == 2 {
			// 代表加入粉丝团
			giftId = "2"
		} else if item.FansClubReasonType == 1 {
			// 代表粉丝团升级
			giftId = "3"
		}

		// 代表加入粉丝团

		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {

		}
		err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID,
			giftId, 1)
		if err != nil {
		}

	}

	fmt.Println("dyPushFans 处理一批加入粉丝团通知成功")

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyGetZhenYing(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" || XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req models.DouYinGetUserGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"dyGetZhenYing error": "invalid request format"})
		return
	}

	fmt.Println("database now : ", config.Get().Database.DataBaseName)

	// 检查 x-roomid 的值
	xRoomId := c.GetHeader("x-roomid")
	if xRoomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	if xRoomId != req.RoomId {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params check error"})
		return
	}

	GameTimes := 1
	status := 1
	var liveRoomInfo *manager.LiveRoomInfo
	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(req.RoomId)
	if err != nil {
		GameTimes = 0
		//// 返回处理结果（根据业务需求调整返回结构）
		//c.JSON(http.StatusOK, gin.H{
		//	"errcode": 0,
		//	"errmsg":  "success",
		//	"data": gin.H{
		//		"round_id":          GameTimes,
		//		"round_status":      2,
		//		"user_group_status": 0,
		//		"group_id":          "",
		//	},
		//})
		//return

		liveRoomInfo = &manager.LiveRoomInfo{
			State: "start",
			Times: 1,
		}
		fmt.Println("触发直播间不存在的时候，给抖音做的专门的查询用户数据，live_room_id : ", req.RoomId)
	}

	GameTimes = liveRoomInfo.Times
	if liveRoomInfo.State == "start" {
		status = 1
	} else {
		status = 2
	}

	userTrackInfo, err := manager.Get().LiveRoomManager().GetLiveTrackInfoByUserId(req.RoomId, req.OpenId)
	if err != nil {
		fmt.Println("dyGetZhenYing 处理查询用户阵营 没有数据",
			", app_id : ", req.AppId,
			", room_id : ", req.RoomId,
			", openid : ", req.OpenId,
		)

		c.JSON(http.StatusOK, gin.H{
			"errcode": 0,
			"errmsg":  "success",
			"data": gin.H{
				"round_id":          GameTimes,
				"round_status":      status,
				"user_group_status": 0,
				"group_id":          "",
			},
		})
		return
	}

	fmt.Println("dyGetZhenYing 处理查询用户阵营 有数据",
		", app_id : ", req.AppId,
		", room_id : ", req.RoomId,
		", openid : ", req.OpenId,
	)

	groupId := strconv.Itoa(userTrackInfo.Track)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"errcode": 0,
		"errmsg":  "success",
		"data": gin.H{
			"round_id":          GameTimes,
			"round_status":      status,
			"user_group_status": 1,
			"group_id":          groupId,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *dyPushController) dyPushZhenYing(c *gin.Context) {
	// 检查 x-roomid 的值
	XSignature := c.GetHeader("X-Signature")
	XTimestamp := c.GetHeader("X-Timestamp")
	if XSignature == "" && XTimestamp == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params not ready"})
		return
	}

	var req models.DouYinPushUserGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"dyGetZhenYing error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	xRoomId := c.GetHeader("x-roomid")
	if xRoomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	if xRoomId != req.RoomId {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params check error"})
		return
	}

	trackNum, err := strconv.Atoi(req.GroupId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "params GroupId check error"})
		return
	}
	err = service.LiveRoomService{}.OneUserJoinTrack(req.RoomId, req.OpenId, req.NickName, req.AvatarUrl, trackNum, 0)
	if err != nil {
		if err.Error() == "user has join live room track " {
			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"message": "success",
				"data":    gin.H{},
			})
			return
		}
		c.JSON(http.StatusBadRequest, gin.H{"error": "dou yin push zhen ying but join error" + err.Error()})
		return
	}

	fmt.Println("dyPushZhenYing 加入阵营成功", "app_id : ", req.AppId,
		"open_id : ", req.OpenId,
		"room_id : ", req.RoomId,
		"group_id : ", req.GroupId,
		"avatar_url : ", req.AvatarUrl,
		"nick_name : ", req.NickName,
	)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 在http_controller.go文件底部添加
var _ routes.Registrar = (*dyPushController)(nil) // 接口实现检查
